<template>
  <div id="components-form-demo-advanced-search">
    <div class="sp_left">
          <div class="sp_left_action">
            <svg @click="addSchoolYears()">
              <use
                xlink:href="../../../../assets/img/icons/all.svg#icon-plus"
              ></use>
            </svg>
          </div>
          <div class="sp_left_text">添加学年</div>
          
          <button class="btn" @click="yearselect()">当前学年</button>
          <button class="btn2" @click="yearselect2()">历届学年</button>
 
        </div>   



    <div
      class="ant-advanced-search-form"
      :form="form"
      @submit="handleSearch"
      v-if="addSchoolYear%2 == 1"
    >


      <div class="threeSelect">
        <div class="select">
          <p class="plabel">教学年份：</p>
          <a-select v-model="year" style="width: 200px">
            <a-select-option
              v-for="(item, index) in yearList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
        <div class="select">
          <p class="plabel">第几学期：</p>
          <a-select v-model="term" style="width: 200px">
            <a-select-option
              v-for="(item, index) in termList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
        <div class="select" >
          <p class="plabel">教学周数：</p>
          <a-select v-model="week" style="width: 200px">
            <a-select-option
              v-for="(item, index) in weekList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
      </div>


        <div class="twoSelect">
          <div class="select">
            <p class="plabel">起止日期：</p>
            <a-range-picker v-model="datevalue" @change="onChange">
            <a-icon slot="suffixIcon" type="smile" />
          </a-range-picker>
          </div>
        </div>
        <div class="submit">
          <div class="select" >
           <p class="plabel">设置为当前学期：</p>
             <a-checkbox @change="onChanges" class="checkbox" :value="item">
               </a-checkbox>
         </div>
         <div class="two-btn">
          <button class="Btn" @click="submit">提交</button>
          <button class="Btn" @click="reset">重置</button>
        </div>
        </div>
        

        
    </div>

    <div class="schoolyear-list">
      <schoolyear-list
        @showSelected="showSelectedSchoolyear"
        @showYearDetail="showNewYear"
        :child_refresh="refresh"
      ></schoolyear-list>
    </div>

    <div class="edityeartime">
      <a-modal v-model="editnewyear_visible" title="编辑课时" @ok="submityear" width="700px">
       
       <div class="edit">
               
          <div class="edit2">
            <p class="ph">教学日每节课时间安排表：</p>
            <a-list size="small" bordered :data-source="data" class="timetable">
            <a-list-item
              :style="{ textAlign: 'center' }"
              slot="renderItem"
              slot-scope="timeitem,index"
            >
              {{ timeitem }} 
              <a-icon type="close"  @click="delone(index)"/>
            </a-list-item>
            <div :style="{ textAlign: 'center' }" slot="header">
              开始时间------｜------结束时间
            </div>
          </a-list>
          </div>

           <div class="edit1">
         <p class="ph">添加时间：</p>
         <div class="addtime">
          <p>开始时间：</p>
          <a-time-picker
            v-model="timestart"
            format="HH:mm"
            @change="onChangeOfStart"
            class="picker"
          />
          <p></p>
          <p>结束时间：</p>
          <a-time-picker
            v-model="timeend"
            format="HH:mm"
            @change="onChangeOfEnd"
            class="picker"
          />
          <p></p>
          <div class="btnn">
          <button @click="addTime" class="Btn">添加</button>
          <button @click="delTime" class="Btn">清空</button>
         </div>
          </div>  
        </div>


       </div>

    </a-modal>

    </div>
    

    <div
      class="ant-advanced-search-form"
      :form="form"
      @submit="handleSearch"
      v-if="editSchoolYear%2 == 1"
    >


      <div class="threeSelect">
        <div class="select">
          <p class="plabel">教学年份：</p>
          <a-select v-model="year" style="width: 200px">
            <a-select-option
              v-for="(item, index) in yearList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
        <div class="select">
          <p class="plabel">第几学期：</p>
          <a-select v-model="term" style="width: 200px">
            <a-select-option
              v-for="(item, index) in termList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
        <div class="select" >
          <p class="plabel">教学周数：</p>
          <a-select v-model="week" style="width: 200px">
            <a-select-option
              v-for="(item, index) in weekList"
              :key="index"
              :value="item"
              >{{ item }}</a-select-option
            >
          </a-select>
        </div>
      </div>


        <div class="twoSelect">
          <div class="select">
            <p class="plabel">起止日期：</p>
            <a-range-picker v-model="datevalue" @change="onChange">
            <a-icon slot="suffixIcon" type="smile" />
          </a-range-picker>
          </div>
        </div>
        <div class="submit">
          <div class="select" >
           <p class="plabel">设置为当前学期：</p>
             <a-checkbox @change="onChanges" class="checkbox" :value="item">
               </a-checkbox>
         </div>
         <div class="two-btn">
          <button class="Btn" @click="submit">提交</button>
          <button class="Btn" @click="reset">重置</button>
        </div>
        </div>
    </div>
  </div>
</template>
<script>
//const courseTimeData = [];@refresh="parent_refresh"

import axiosInstance from "@/utils/axios";
import { mapState } from "vuex";
import axios from "@/utils/axios";
import moment from "moment";
import SchoolyearList from "./SchoolyearList";

export default {
  components: { SchoolyearList },

  data() {
    return {
      form: this.$form.createForm(this, { name: "advanced_search" }),
      week: "请选择周数",
      year: "请选择学年",
      term: "请选择学期",
      datevalue: null,
      seme: "否",
      SemeList: ["是", "否"],
      weekList: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5],
      termList: [1, 2, 3, 4],
      startTime: "", //moment().format("HH:MM"),
      endTime: "", //moment().format("HH:MM"),
      addSchoolYear:0,
      editSchoolYear:0,
      editnewyear_visible:0,
      timestart: "",
      timeend: "",
      startDate: "",
      endDate: "",
      changeTime:[],
      data: [],
      coursetime:{
        begin_time:[],
        end_time:[],
      },
      timeitem: [],
      refresh: 1,
      index: 1,
      indexs:[],
      oneSY: {},
    };
  },
  computed: {
    yearList() {
      let year = moment().year();
      return [
        year - 2 + "-" + (year - 1),
        year - 1 + "-" + year,
        year + "-" + (year + 1),
        year + 1 + "-" + (year + 2),
      ];
    },
    ...mapState({
      Tree_spin_status: (state) => state.admin.Tree_spin_status,
      uid: (state) => state.public.uid,
      oid: (state) => state.public.oid,
      org_name: (state) => state.public.orgName,
    }),
  },

  mounted() {
    //this.$store.dispatch("public/getCurrentSchoolYear");
    //this.$store.dispatch("public/getOrgnizationName", this.oid);
  },
  methods: {
    onChanges(e) {
      console.log(`checked = ${e.target.checked}`);
      this.seme = "是";
    },
    moment,
    // parent_refresh(ss) {
    //   this.refresh += ss;
    // },
    showNewYear(record,val){
      this.editnewyear_visible = val
        this.timestart = "";
        this.timeend = "";
        this.year = record.year;
        this.week = record.weeks;
        this.term = record.semester;
        this.startDate = moment(record.start_time).format("YYYY-MM-DD");
        this.endDate = moment(record.end_time).format("YYYY-MM-DD");
        this.datevalue = [
          moment(record.start_time, "YYYY-MM-DD"),
          moment(record.end_time, "YYYY-MM-DD"),
        ];
        this.seme = record.current;
        this.course_time = record.course_time;
        this.data = [];
        let tmp = [];
        for (let i = 0; i < record.course_time.length; i++) {
          this.index = i + 1;
          this.startTime = record.course_time[i].begin_time;
          this.endTime = record.course_time[i].end_time;
          this.timeitem =
            "第" +
            this.index +
            "节课： " +
            this.startTime +
            " 至 " +
            this.endTime;
          tmp.push(this.timeitem);
        }
    },
    showSelectedSchoolyear(record,val) {
      console.log(val);
      this.editSchoolYear = val;
      if (record != null) {
        this.year = record.year;
        this.week = record.weeks;
        this.term = record.semester;
        this.startDate = moment(record.start_time).format("YYYY-MM-DD");
        this.endDate = moment(record.end_time).format("YYYY-MM-DD");
        this.datevalue = [
          moment(record.start_time, "YYYY-MM-DD"),
          moment(record.end_time, "YYYY-MM-DD"),
        ];
        this.seme = record.current;
        this.course_time = record.course_time;
        this.data = [];
        let tmp = [];
        for (let i = 0; i < record.course_time.length; i++) {
          this.index = i + 1;
          this.startTime = record.course_time[i].begin_time;
          this.endTime = record.course_time[i].end_time;
          this.timeitem =
            "第" +
            this.index +
            "节课： " +
            this.startTime +
            " 至 " +
            this.endTime;
          tmp.push(this.timeitem);
        }
        this.data = tmp;
        if (record.course_time.length != 0) this.index++;
        this.startTime = "";
        this.endTime = "";
        this.oneSY = record;
      } else {
        this.week = "请选择周数";
        this.year = "请选择学年";
        this.term = "请选择学期";
        this.datevalue = "";
        this.seme = "否";
        this.timestart = "";
        this.timeend = "";
        this.oneSY = {};
        this.delTime();
      }
    },
    yearselect(){
      // document.getElementsByName("btn").className = "btn2";
      document.getElementsByName("btn2").className = "btn";
    },
    yearselect2(){
      document.getElementsByName("btn").className = "btn2";
      document.getElementsByName("btn2").className = "btn";
    },
    reset() {
      this.week = "请选择周数";
      this.year = "请选择学年";
      this.term = "请选择学期";
      this.datevalue = null;
      this.seme = "否";
      this.timestart = "";
      this.timeend = "";
      this.oneSY = {};
      this.delTime();
    },
    handleSearch(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {});
    },
    addTime() {
      // if (this.startTime === "" || this.endTime === "")
      //   this.$message.error("请选择开始和结束时间");
      // else if(this.startTime >= this.endTime ){
      //   this.$message.error("开始时间要早于结束时间");
      // }
      // else if(this.startTime < this.changeTime ){
      //   this.$message.error("课程时间冲突");
      // }
      // else {
        this.timeitem =
          "第" +
          this.index +
          "节课： " +
          this.startTime +
          " 至 " +
          this.endTime;
        this.index += 1;
        this.indexs.push(this.index);
        this.coursetime.begin_time.push(this.startTime);
        this.coursetime.end_time.push(this.endTime);
        this.data.push(this.timeitem);
        this.changeTime.push(this.endTime);
      // }
    },
    delone(index){
      this.data.splice(index,1);
      if(this.data == ""){
        this.index = 1;
        this.changeTime.splice(index,1);
      }
      else if( (index+2) == this.index){    
        this.changeTime.splice(index,1);
        this.index -=1;
      }
      else{
        this.indexs.splice(index,1);
      }
    },
    delTime() {
      this.course_time = [];
      this.data = [];
      this.index = 1;
    },
    addSchoolYears(){
      this.addSchoolYear = this.addSchoolYear + 1;
      this.term = "请选择学期";
      this.week = "请选择周数";
      this.year = "请输入学年";
      this.datevalue = "";
    },
    submit() {
      let isCurrent = "f";
      if (this.seme === "是") isCurrent = "t";
      console.log(this.course_time);
      const postData = {
        org_name: this.org_name,
        start_time: this.startDate,
        end_time: this.endDate,
        current: isCurrent,
        weeks: Number.parseInt(this.week),
        year: this.year,
        semester: Number.parseInt(this.term),
        course_time: this.coursetime,
      };
      if (this.seme === "是") {
        axios
          .post("pc/v1/schoolyears/changeCurrentSYtoNomarl")
          .then(({ data }) => {
            // console.log(data);
            const { status } = data;
            if (!status) throw "fail";
          })
          .catch((err) => {
            console.error(err);
          });
      }

      if (this.oneSY._id == null) {
        //add a new schoolyear record
        if (
          this.week != "请选择周数" &&
          this.year != "请选择学年" &&
          this.term != "请选择学期"
        ) {
          axios
            .post("pc/v1/schoolyears/addSchoolYear", postData)
            .then(({ data }) => {
              const { status } = data;
              if (!status) throw "fail";
              this.$message.success("学年创建成功");
              this.refresh += 1;
            })
            .catch((err) => {
              console.error(err);
              this.$message.error("学年创建失败");
            });
        } else {
          this.$message.error("请选择学年、学期、周数等必备信息！");
        }
      } else {
        //update the selected schoolyear record
        axios
          .patch("pc/v1/schoolyears/" + this.oneSY._id, postData)
          .then(({ data }) => {
            const { status } = data;
            if (!status) throw "fail";
            this.$message.success("学年更新成功");
            this.refresh += 1;
          })
          .catch((err) => {
            console.error(err);
            this.$message.error("学年更新失败");
          });
      }
      this.addSchoolYear = 0;
      this.editSchoolYear = 0;
    },
    submityear() {
      let isCurrent = "f";
      if (this.seme === "是") isCurrent = "t";
      console.log(this.coursetime);
      const postData = {
        org_name: this.org_name,
        start_time: this.startDate,
        end_time: this.endDate,
        current: isCurrent,
        weeks: Number.parseInt(this.week),
        year: this.year,
        semester: Number.parseInt(this.term),
        course_time: this.coursetime,
      };

      axios
          .patch("pc/v1/schoolyears/" + this.oneSY._id, postData)
          .then(({ data }) => {
            const { status } = data;
            if (!status) throw "fail";
            this.$message.success("学时编辑成功");
            this.refresh += 1;
          })
          .catch((err) => {
            console.error(err);
            this.$message.error("学时编辑失败");
          });
      this.addSchoolYear = 0;
      this.editSchoolYear = 0;
      this.editnewyear_visible = false;
    },

    onChange(date, dateString) {
      //console.log(date, dateString);
      this.startDate = dateString[0];
      this.endDate = dateString[1];
      console.log(this.startDate + "+" + this.endDate);
    },
    onChangeOfStart(time, timeString) {
      this.startTime = timeString;
      //console.log(time, timeString);
    },
    onChangeOfEnd(time, timeString) {
      this.endTime = timeString;
      //console.log(time, timeString);
    },
  },
  watch: {
    //refresh(val) {
    // this.getStudents();
    //},
  },
};
</script>
<style lang="scss">
.ant-advanced-search-form {
  position: relative;
  width: 1220px;
  padding: 24px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  margin: 10px 12px 0px 0px;
  // display: flex;
}

.ant-advanced-search-form .ant-form-item {
  display: flex;
}

.ant-advanced-search-form .ant-form-item-control-wrapper {
  flex: 1;
}

#components-form-demo-advanced-search .ant-form {
  max-width: none;
}
#components-form-demo-advanced-search .result-list {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  padding-top: 80px;
}
.ant-table-small > .ant-table-content > .ant-table-body {
  margin: 0;
}
.twoSelect{
  margin: 0px 0px 0px 40px;
  display: flex;
  padding: 10px;
}
.submit{
  margin: 0px 0px 0px 40px;
  // display: flex;
  padding: 10px;
}
.btn{
  margin:0px 12px 0px 0px;
  background-color: #4ABAC4;
  border-radius: 5px;
  margin-right: 10px;
  margin: 0 10px 0 10px;
  font-size: 15px;
  border: 1px solid #4ABAC4;
  padding: 0.5rem 1.5rem;
  cursor: pointer;
}
.btn:hover{
  background-color: #4ABAC4;
  color: #FFF;
}
.btn:active{
  transform: translateY(1px);
}
.btn2{
  margin:0px 12px 0px 0px;
  background-color: #FFF;
  border-radius: 5px;
  margin-right: 10px;
  margin: 0 10px 0 10px;
  font-size: 15px;
  border: 1px solid #4ABAC4;
  padding: 0.5rem 1.5rem;
  cursor: pointer;
}
.btn2:hover{
  background-color: #4ABAC4;
  color: #FFF;
}
.btn2:active{
  transform: translateY(1px);
}
.sp_left_text{
  margin: 0px 12px 0px 0px;
}
.select{
  margin: 0px 30px 0px 0px;
  display: flex;
}
.threeSelect{
  margin: 0px 0px 0px 40px;
  padding: 10px;
  display: flex;
}
.plabel{
  margin: 5px 0px 0px 0px;
}
.checkbox{
  margin: 5px 0px 0px 0px;
}
.schoolyear-list{
  position: relative;
  width: 1220px;
}
.Btn{
  // width: 100px;
  margin:0px 12px 0px 0px;
  color: #ffffff;
  background-color: #4ABAC4;
  border-radius: 5px;
  margin-right: 10px;
  margin: 0 10px 0 10px;
  font-size: 15px;
  border: 1px solid #4ABAC4;
  padding: 0.5rem 1.5rem;
  cursor: pointer;
}
.Btn:hover{
  background-color: $color-primary;
  color: #FFF;
}
.two-btn{
  float: right;
  margin:-10px 12px 0px 0px;
}
.editTime{
  height: 2000px;
}
.edit{
  display: flex;
}
.edit1{
  float: right;
  height: 250px;
  margin:0px 0px 0px 30px;
}
.edit2{
  width: 60%;
  height: 250px;
}
.btnn{
  display: flex;
  margin:0px 0px 0px 5px;
}
.timetable{
  margin: -10px 0px 0px 0px;
  position: relative;
  // height: 415px;
}
.picker{
  width: 200px;
}
.ph{
  color: #4ABAC4;
  font-size: 20px;
}
.addtime{
  margin: 0px 0px 0px 0px;
}
</style>
